package com.android.kotlincoroutinemvvmdemo.view
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.core.view.get

class UnspecifiedLayout @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : LinearLayoutCompat(context,attributeSet) {

    private var downY = 0

    private var totalMovedY = 0

    private var mScreenHeight = 0

    private var mViewHeight = 0

    private var canMove = false

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        //MeasureSpec.UNSPECIFIED 代表一种特殊的情况，表示父视图没有对子视图施加任何约束，也就是说父视图没有对子视图的大小有明确的要求。
        //这种情况通常发生在自定义布局或没有布局参数的情况下，系统希望子视图根据自己的内容和内部策略来决定自己的尺寸。
        //MeasureSpec.UNSPECIFIED对高度没有限制,那么测量出来的就是完全展示内容所需的高度.
        val mNewHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
        super.onMeasure(widthMeasureSpec, mNewHeightMeasureSpec)
        mScreenHeight = context.resources.displayMetrics.heightPixels
        mViewHeight = measuredHeight
        canMove = mViewHeight - mScreenHeight > 0
        Log.d(TAG, "heightPixels:${context.resources.displayMetrics.heightPixels}")
        Log.d(TAG, "measuredHeight:${measuredHeight}")
        Log.d(TAG, "get(0).measuredHeight:${get(0).measuredHeight}")
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        performClick()
        when (event?.action) {
            MotionEvent.ACTION_DOWN -> {
                downY = event.y.toInt()
            }
            MotionEvent.ACTION_MOVE -> {
                val moveY = event.y.toInt()
                totalMovedY += (downY - moveY)
                Log.d(TAG, "before---totalMovedY:${totalMovedY}")
                totalMovedY = Math.max(0, Math.min(totalMovedY, mViewHeight - mScreenHeight))
                Log.d(TAG, "after---totalMovedY:${totalMovedY}")
                scrollTo(0, totalMovedY)
                downY = moveY
            }
        }
        return canMove
    }

    override fun performClick(): Boolean {
        return super.performClick()
    }

    companion object {
        const val TAG = "UnspecifiedLayout"
    }
}